package org.lex.ftp.ui.find.filter;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.lex.filter.BooleanFilter;
import org.lex.filter.Filter;
import org.lex.filter.Filters;
import org.lex.swing.Swings;

public class FileTypeFilterPane extends JPanel implements Filter<Boolean>, ItemListener {
	private static final String[] TYPES = { "Files and Folders", "Files Only", "Folders Only" };
	private JPanel fileTypePane = null;
	private JLabel generalTypeLabel = null;
	private JComboBox generalTypeComboBox = null;
	private Filter<Boolean> filter = Filters.acceptAllFilter();

	public static void main(String[] args) {
		Swings.show(new FileTypeFilterPane());
	}

	public FileTypeFilterPane() {
		super();
		initialize();
	}

	public Filter<Boolean> getFilter() {
		return this.filter;
	}

	public boolean accept(Boolean b) {
		return filter.accept(b);
	}

	public void itemStateChanged(ItemEvent e) {
		if (e.getStateChange() == ItemEvent.DESELECTED)
			return;
		int type = this.getGeneralTypeComboBox().getSelectedIndex();
		if (0 == type)
			filter = Filters.acceptAllFilter();
		else if (1 == type)
			filter = new BooleanFilter(false, TYPES[1]);
		else if (2 == type)
			filter = new BooleanFilter(true, TYPES[2]);
		System.out.println(filter);
	}

	// =======================
	private void initialize() {
		this.setSize(300, 200);
		this.setLayout(new BorderLayout());
		this.add(getFileTypePane(), BorderLayout.NORTH);
	}

	private JPanel getFileTypePane() {
		if (fileTypePane == null) {
			FlowLayout flowLayout = new FlowLayout();
			flowLayout.setAlignment(FlowLayout.LEFT);
			flowLayout.setAlignOnBaseline(true);
			generalTypeLabel = new JLabel();
			generalTypeLabel.setText("Type");
			fileTypePane = new JPanel();
			fileTypePane.setLayout(flowLayout);
			fileTypePane.setBorder(BorderFactory.createTitledBorder("File Type"));
			fileTypePane.add(generalTypeLabel, null);
			fileTypePane.add(getGeneralTypeComboBox(), null);
		}
		return fileTypePane;
	}

	private JComboBox getGeneralTypeComboBox() {
		if (generalTypeComboBox == null) {
			generalTypeComboBox = new JComboBox();
			for (String type : TYPES)
				generalTypeComboBox.addItem(type);
			generalTypeComboBox.setSelectedIndex(0);
			generalTypeComboBox.addItemListener(this);
		}
		return generalTypeComboBox;
	}
}
